<?php
@header("Content-type: text/html; charset=utf-8");
session_start();
if (isset($_SESSION[realpath("..") . 'admin']) && $_SESSION[realpath("..") . 'admin'] == true) {
} else {
    $_SESSION[realpath("..") . 'admin'] = false;
    echo "<script>window.location='login.php';</script>";
    die;
}
include("db.php");
if (isset($_GET['do'])) {
    $do = $_GET['do'];
    @$cid = $_GET['cid'];
    @$config = $_GET['cof'];
} else {
    die("invild action");
}

switch ($do) {
    case "savemenu":
        savemenu();
        break;
    case "updateweixinmenu":
    	updateweixinmenu();
    	break;
	case "delmenu":
		delmenu();
    	break;
}
function savemenu(){
	$params=$_POST;
	$params['pid']=isset($params['pid'])?intval($params['pid']):0;
	$params['name']=isset($params['name'])?strval($params['name']):'';
	$params['type']=isset($params['type'])?strval($params['type']):'';
	$params['val']=isset($params['val'])?strval($params['val']):'';
	if($params['name']==''){
		echo '{"error":-1,"error_msg":"菜单名必须填写"}';
		return ;
	}

	$weixinmenu_m=new M('weixinmenu');
	if($params['pid']==0){
		$data=$weixinmenu_m->select('pid=0');

		if(count($data)>=3){
			echo '{"error":-2,"error_msg":"顶级菜单不能超过3个"}';
			return ;
		}
	}
	$return=$weixinmenu_m->add($params);
	if($return){
		echo '{"error":1,"error_msg":"保存成功"}';
		return ;
	}else{
		echo '{"error":-3,"error_msg":"保存失败"}';
		return ;
	}
}
function updateweixinmenu(){
	require_once('../common/function.php');
	require_once('../common/http_helper.php');
	require_once('../common/weixin_helper.php');
    $weixinconf = getWeixinConf();
    $baseaccesstoken=getbaseaccess_token($weixinconf['appid'],$weixinconf['appsecret']);
    // $baseaccesstokeninfo=$baseaccesstoken;
	$data=menujson();
	$url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$baseaccesstoken['access_token'];
	$return_json=http_post($url,$data);
	$return=json_decode($return_json,true);
	if($return['errcode']==0){
		echo '{"error":1,"error_msg":"更新成功"}';
		return;
	}else{
		echo '{"error":-1,"error_msg":"'.$return['errmsg'].'"}';
		return;
	}
}

function menujson(){
	$weixinmenu_m=new M('weixinmenu');
	$data=$weixinmenu_m->select('1');
	// echo var_export($data);
	$menudata=array();
	foreach($data as $k=>$v){
		$item=array();
	    if($v['pid']==0){
	    	$item['id']=$v['id'];
	    	$item['name']=$v['name'];
	    	$item['type']=$v['type'];
	    	if($v['type']=='click'){
	    		$item['key']=$v['val'];
	    	}
	    	if($v['type']=='view'){
	    		$item['url']=$v['val'];
	    	}
	        $menudata[]=$item;
	    }
	    if($v['pid']>0){
	        for($i=0,$l=count($menudata);$i<$l;$i++){
	            if($menudata[$i]['id']==$v['pid']){
	            	$item['name']=$v['name'];
	            	$item['type']=$v['type'];
	            	if($v['type']=='click'){
			    		$item['key']=$v['val'];
			    	}
			    	if($v['type']=='view'){
			    		$item['url']=$v['val'];
			    	}
	                $menudata[$i]['sub_button'][]=$item;
	            }
	        }
	    }
	}
	foreach($menudata as $k=>$v){
		unset($menudata[$k]['id']);
	}
	$menudata_json=json_encode_ex($menudata);
	return '{"button":'.$menudata_json.'}';
}
function json_encode_ex( $value) 
{ 
	if ( version_compare( PHP_VERSION,'5.4.0','<')) { 
		$str = json_encode( $value); 
		$str =  preg_replace_callback("#\\\u([0-9a-f]{4})#i", function( $matchs) { 
			return  iconv('UCS-2BE', 'UTF-8',  pack('H4',  $matchs[1])); 
		}, $str); 
		return  $str; 
	} 
	else 
	{ 
		return json_encode( $value, JSON_UNESCAPED_UNICODE); 
	}
}
function delmenu(){
	$params=$_POST;
	$params['id']=isset($params['id'])?intval($params['id']):0;
	if($params['id']<=0){
		echo '{"error":-1,"error_msg":"删除失败"}';
		return;
	}
	$weixinmenu_m=new M('weixinmenu');
	$data=$weixinmenu_m->select('pid='.$params['id']);
	if(count($data)>0){
		foreach($data as $item){
			$weixinmenu_m->delete('id='.$item['id']);
		}
	}
	$return=$weixinmenu_m->delete('id='.$params['id']);
	if($return){
		echo '{"error":1,"error_msg":"删除成功"}';
		return;
	}
	echo '{"error":-2,"error_msg":"删除失败"}';
	return;
}